package com.binfenhulian.chinaenergy.ces.utils.string;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Collection;
import java.util.Random;
import java.util.StringJoiner;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * StringUtils工具类
 * Created by PengSongHe on 2016/5/11.
 */
public class StringUtils {
    public StringUtils() {
    }

    public static String covertEmptyToNUll(String input){
        if (StringUtils.isEmpty(input)){
            return null;
        }
        return  input;
    }

    /**
     * 连接字符串
     * @param collection
     * @param delimiter
     * @return
     */
    public static String join(Collection collection,CharSequence delimiter){
        StringJoiner sj = new StringJoiner(delimiter);
        for (Object o : collection) {
            sj.add(o.toString());
        }
        return sj.toString();
    }

    /**
     * 字符串空值判断
     *
     * @param str 字符串
     * @return true 空 false 非空
     */
    public static boolean isEmpty(String str) {
        return null == str || str.trim().length() == 0 || str.toString().trim().equalsIgnoreCase("null") || str.toString().trim().equalsIgnoreCase("(null)");
    }

    /**
     * 字符串非空判断
     *
     * @param str 字符串
     * @return true 非空 false 空
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * 百分比格式化数字
     *
     * @param n
     * @return
     */
    public static String fromtPercent(double n) {
        //获取常规数值格式
        NumberFormat numFormat = NumberFormat.getPercentInstance();
        numFormat.setMaximumIntegerDigits(3); //设置数的 整数 部分所允许的最小位数(如果不足后面补0)
        numFormat.setMaximumFractionDigits(2);//设置数的 小数 部分所允许的最大位数(如果超过会四舍五入)
        return numFormat.format(n);
    }

    /**
     * 货币
     *
     * @param n
     * @return
     */
    public static String fromtCurrency(double n) {
        //获取常规数值格式
        NumberFormat numFormat = NumberFormat.getCurrencyInstance();//NumberFormat.getCurrencyInstance(Locale.US);
        return numFormat.format(n);
    }

    /**
     * 手机号码屏蔽处理
     *
     * @param mobile 手机号
     * @return String 例 183****4036
     */
    public static String starMobile(String mobile) {
        if (mobile.length() == 11) {
            String starmobile = mobile.charAt(0) + String.valueOf(mobile.charAt(1)) + mobile.charAt(2) + "****" + mobile.charAt(7) + mobile.charAt(8) + mobile.charAt(9) + mobile.charAt(10);
            return starmobile;
        } else {
            return mobile;
        }
    }

    /**
     * 邮箱屏蔽处理
     *
     * @param email 邮箱
     * @return String
     */
    public static String handleEmail(String email) {
        if (email == null) {
            return "";
        } else {
            String[] aryEmail = email.split("@");
            if (aryEmail != null && aryEmail.length == 2 && aryEmail[0] != null) {
                String firstPart = aryEmail[0].substring(aryEmail[0].length() / 2, aryEmail[0].length());
                if (firstPart != null && !"".equals(firstPart)) {
                    char[] repeatChar = new char[firstPart.length()];

                    for (int i = 0; i < firstPart.length(); ++i) {
                        repeatChar[i] = 42;
                    }

                    email = email.replaceFirst(firstPart + "@", new String(repeatChar) + "@");
                }
            }

            return email;
        }
    }

    /**
     * 获取指定长度的随机字符串
     *
     * @param strLength 指定长度
     * @return string
     */
    public static String getRandomString(int strLength) {
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();

        for (int i = 0; i < strLength; ++i) {
            int charInt;
            char c;
            if (random.nextBoolean()) {
                charInt = 48 + random.nextInt(10);
                c = (char) charInt;
                buffer.append(c);
            } else {
                boolean var6 = true;
                if (random.nextBoolean()) {
                    charInt = 65 + random.nextInt(26);
                } else {
                    charInt = 97 + random.nextInt(26);
                }

                if (charInt == 79) {
                    charInt = 111;
                }

                c = (char) charInt;
                buffer.append(c);
            }
        }

        return buffer.toString();
    }

    /**
     * 获取指定长度的随机数字字符串
     *
     * @param n 指定长度
     * @return string
     */
    public static String getRandNumStr(int n) {
        Random random = new Random();
        String sRand = "";

        for (int i = 0; i < n; ++i) {
            String rand = String.valueOf(random.nextInt(10));
            sRand = sRand + rand;
        }

        return sRand;
    }

    /**
     * 获取系统随机
     *
     * @param count 指定长度
     * @return string
     */
    public static String getSysTimeRandom(int count) {
        String resultRandom = System.currentTimeMillis() + "" + (new Random()).nextInt(100);
        String resultRandomPro = "";
        int resultCount = resultRandom.length();
        if (count < resultCount) {
            return resultRandom.substring(resultCount - 1 - count, resultCount - 1);
        } else {
            for (int i = 0; i < count - resultCount; ++i) {
                resultRandomPro = resultRandomPro + "0";
            }

            return resultRandomPro + resultRandom;
        }
    }

    /**
     * 字符串相等判断
     *
     * @param str1 字符串1
     * @param str2 字符串2
     * @return true 相等 false 不相等
     */
    public static boolean equals(String str1, String str2) {
        return str1 != null && !str1.equals("") && str2 != null && !str2.equals("") ? str1.equals(str2) : false;
    }

    /**
     * 字符串转int
     *
     * @param str 字符串
     * @return int
     */
    public static int toInt(String str) {
        boolean value = false;
        if (str != null && !str.equals("")) {
            int value1;
            try {
                value1 = Integer.parseInt(str);
            } catch (Exception var3) {
                var3.printStackTrace();
                value1 = 0;
            }

            return value1;
        } else {
            return 0;
        }
    }

    /**
     * 数组转字符串
     *
     * @param array 数组 例 {"123","456","789"}
     * @param split 分隔符 例 “|”
     * @return string 例 123|456|789
     */
    public static String arrayToString(Object[] array, String split) {
        if (array == null) {
            return "";
        } else {
            StringBuffer str = new StringBuffer("");
            for (int i = 0; i < array.length; ++i) {
                if (i != array.length - 1) {
                    str.append(array[i].toString()).append(split);
                } else {
                    str.append(array[i].toString());
                }
            }

            return str.toString();
        }
    }

    /**
     * 字符串转文件大小
     *
     * @param fileSize
     * @return string
     */
    public static String getFileSize(String fileSize) {
        String temp = "";
        DecimalFormat df = new DecimalFormat("0.00");
        double dbFileSize = Double.parseDouble(fileSize);
        if (dbFileSize >= 1024.0D) {
            if (dbFileSize >= 1048576.0D) {
                if (dbFileSize >= 1.073741824E9D) {
                    temp = df.format(dbFileSize / 1024.0D / 1024.0D / 1024.0D) + " GB";
                } else {
                    temp = df.format(dbFileSize / 1024.0D / 1024.0D) + " MB";
                }
            } else {
                temp = df.format(dbFileSize / 1024.0D) + " KB";
            }
        } else {
            temp = df.format(dbFileSize / 1024.0D) + " KB";
        }

        return temp;
    }

    /**
     * 转utf-8 编码
     *
     * @param str 字符串
     * @return string
     */
    public static String toUTF8(String str) {
        return to(str, "UTF-8");
    }

    /**
     * 字符串转指定编码
     *
     * @param str     字符串
     * @param charset 编码格式
     * @return string
     */
    public static String to(String str, String charset) {
        if (str != null && !str.equals("")) {
            try {
                return new String(str.getBytes("ISO8859-1"), charset);
            } catch (Exception var3) {
                var3.printStackTrace();
                return "";
            }
        } else {
            return "";
        }
    }

    /**
     * 数字转中文
     *
     * @param num 数字
     * @return string
     */
    public static String getChineseNum(int num) {
        String[] chineseNum = new String[]{"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
        return chineseNum[num];
    }

    /**
     * 去除回车换行字符
     *
     * @param str 字符串
     * @return string
     */
    public static String replaceEnter(String str) {
        return str == null ? null : str.replaceAll("\r", "").replaceAll("\n", "");
    }

    /**
     * 去除空格
     *
     * @param strtrim
     * @return
     */
    public static String toTrim(String strtrim) {
        return null != strtrim && !strtrim.equals("") ? strtrim.trim() : "";
    }

    /**
     * 获取html中的内容（去除html标签）
     *
     * @param element html字符串
     * @return string
     */
    public static String getTxtWithoutHTMLElement(String element) {
        if (null == element) {
            return element;
        } else {
            Pattern pattern = Pattern.compile("<[^<|^>]*>");
            Matcher matcher = pattern.matcher(element);
            StringBuffer txt = new StringBuffer();

            String temp;
            while (matcher.find()) {
                temp = matcher.group();
                if (temp.matches("<[\\s]*>")) {
                    matcher.appendReplacement(txt, temp);
                } else {
                    matcher.appendReplacement(txt, "");
                }
            }

            matcher.appendTail(txt);
            temp = txt.toString().replaceAll("[\r|\n]", "");
            temp = temp.replaceAll("\\s+", " ");
            return temp;
        }
    }

    public static String createUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }

    /**
     * 截取添加追加字符
     *
     * @param sourceStr 源字符串
     * @param length    截取的位置
     * @param charactor 追加的字符
     * @return
     */
    public static String cutffStr(String sourceStr, int length, String charactor) {
        String resultStr = sourceStr;
        if (sourceStr != null && !"".equals(sourceStr)) {
            if (sourceStr.length() > length) {
                resultStr = sourceStr.substring(0, length);
                resultStr = resultStr + charactor;
            }

            return resultStr;
        } else {
            return "";
        }
    }

    /**
     * 截串，超过长度 省略
     *
     * @param goodsName
     * @param length
     * @return
     */
    public static String getLength(Object goodsName, int length) {
        if (goodsName == null) {
            return null;
        } else {
            String temp = String.valueOf(goodsName);
            if (temp.length() <= length) {
                return temp;
            } else {
                temp = temp.substring(0, length) + "...";
                return temp;
            }
        }
    }

    /**
     * 追加字符
     *
     * @param s1 字符串1
     * @param s2 字符串2
     * @return
     */
    public static String stringAppend(String s1, String s2) {
        if (isEmpty(s1)) {
            return s2;
        }
        if (isEmpty(s2)) {
            return s1;
        }
        StringBuilder builder = new StringBuilder(s1);
        builder.append(",").append(s2);
        return builder.toString();
    }

    /**
     * 将过长字符串进行截取，并在末尾追加描述符，如...
     *
     * @param str       要截取的字符串
     * @param maxLength 最大长度
     * @param replace   追加的字符串，如果是null，则默认为...
     * @return 截取结果
     */
    public static String cut(String str, int maxLength, String replace) {
        //检查是否为空
        if (StringUtils.isEmpty(str)) {
            return str;
        }
        //检查replace是否存在
        if (replace == null) {
            replace = "...";
        }
        //检查长度
        if (str.length() + replace.length() <= maxLength || maxLength < 1 || replace.length() > maxLength) {
            return str;
        }
        //开始截取
        return str.substring(0, maxLength - replace.length()) + replace;
    }

    public static boolean yesNull(String str)
    {
        return (str == null) || (str.length() <= 0);
    }

    public static boolean notNull(String str)
    {
        return !yesNull(str);
    }

    public static String notNullStr(String str)
    {
        return (yesNull(str)) || ("NULL".equals(str)) ? "" : str;
    }

    public static String strorkong(String str)
    {
        return notNull(str) ? str : "";
    }

    public static String addZeroForNum(String str, int strLength)
    {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < strLength - str.length(); i++) {
            sb.append("0");
        }
        sb.append(str);
        return sb.toString();
    }

    public static String reverse(String str) {
        return new StringBuffer(str).reverse().toString();
    }
}

